import config from './config'

export default {
  config: config,

  initData() {
    return {
      version: this.config.version,
      state: {
        scene: 'plot',
        polt: {
          name: 'start'
        }
      }
    }
  },

  init() {
    return new Promise((resolve, reject) => {
      let request = window.indexedDB.open(this.config.name)
      let firstFlag = false
      let db

      request.onupgradeneeded = (e) => {
        firstFlag = true
        db = request.result
        this.firstCreate(db).then(() => {
          resolve(this.initData())
        })
      }

      request.onsuccess = (e) => {
        if (!firstFlag) {
          db = request.result
          this.read(db).then((response) => {
            resolve(response.data)
          })
        }
      }
    })
  },

  read(db) {
    return new Promise((resolve, reject) => {
      let request = db.transaction(['save'], 'readonly')
        .objectStore('save')
        .get('save')

      request.onsuccess = function (event) {
        request.result.data = JSON.parse(decodeURIComponent(atob(request.result.data)))
        resolve(request.result)
      }
    })
  },

  firstCreate(db) {
    return new Promise((resolve, reject) => {
      if (!db.objectStoreNames.contains('save')) {
        db.createObjectStore('save', { keyPath: 'name' })
        let request = window.indexedDB.open(this.config.name)

        request.onsuccess = (e) => {
          let db = request.result
          let saveData = {
            name: 'save',
            data: btoa(encodeURIComponent(JSON.stringify(this.initData())))
          };

          db.transaction(['save'], 'readwrite')
            .objectStore('save')
            .add(saveData)
            .onsuccess = function (e) {
              resolve()
            }
        }
      }
      else {
        resolve({})
      }
    })
  },

  reset() {
    indexedDB.deleteDatabase(this.config.name)
  }
}